﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Collections.ObjectModel;
using SevenDrops.Domain;
using Microsoft.Phone.Tasks;
using System.Diagnostics;
using System.IO.IsolatedStorage;
using System.Text;
using System.Security.Cryptography;
using SevenDrops.Helpers;
using System.Windows.Data;
using System.Windows.Controls.Primitives;

namespace SevenDrops
{
    public partial class MainPage : PhoneApplicationPage
    {
        DependencyProperty _collection = DependencyProperty.Register("ImageCollection", typeof(ObservableCollection<ImageUnit>), typeof(MainPage), null);
        public ObservableCollection<ImageUnit> Images
        {
            get
            {
                return (ObservableCollection<ImageUnit>)GetValue(_collection);
            }
            set
            {
                SetValue(_collection, value);
            }
        }

        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Images = new ObservableCollection<ImageUnit>();
            Debug.WriteLine(GenerateRandom64Bit());

            Debug.WriteLine("Token: {0}", IsolatedStorageSettings.ApplicationSettings["token"].ToString());
            Debug.WriteLine("Secret: {0}", IsolatedStorageSettings.ApplicationSettings["secret"].ToString());

            App.mainPageDisp = Dispatcher;
        }



        string GenerateRandom64Bit()
        {
            byte[] set = new byte[8];
            Random random = new Random();
            random.NextBytes(set);

            string toReturn = BitConverter.ToUInt64(set, 0).ToString();

            return toReturn;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            PhotoChooserTask task = new PhotoChooserTask();
            task.Completed += new EventHandler<PhotoResult>(task_Completed);
            task.Show();
        }

        void task_Completed(object sender, PhotoResult e)
        {
            ImageUnit unit = new ImageUnit();
            unit.ImageName = Guid.NewGuid().ToString() + ".jpg";
            byte[] b = new byte[e.ChosenPhoto.Length];
            e.ChosenPhoto.Read(b, 0, Convert.ToInt32(e.ChosenPhoto.Length));
            unit.ImageContents = b;

            Images.Add(unit);
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("/Credentials.xaml", UriKind.Relative));
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            string token = IsolatedStorageSettings.ApplicationSettings["token"].ToString();
            string tokenSecret = IsolatedStorageSettings.ApplicationSettings["secret"].ToString();

            App.uploadCounter.Counter = ImageList.Items.Count;

            foreach (ImageUnit unit in Images)
            {
                OAuth.OAuthClient.Upload(unit.ImageName, unit.ImageContents, token, Helpers.Constants.ApiKey, Helpers.Constants.ConsumerSecret, tokenSecret);
            }

            Popup uploadPopup = new Popup();
            uploadPopup.Child = new UploadingFiles();
            uploadPopup.IsOpen = true;
            uploadPopup.VerticalOffset = 100;
            uploadPopup.HorizontalOffset = 25;

            Binding b = new Binding();
            b.Source = App.uploadCounter;
            b.Converter = new CounterToVisibilityConverter();
            b.Path = new PropertyPath("Counter");
            uploadPopup.SetBinding(Popup.IsOpenProperty, b);
        }

        private void Button_Click_2(object sender, RoutedEventArgs e)
        {
            FrameworkElement n = (FrameworkElement)((Button)sender).Parent;
            TextBlock t = (TextBlock)n.FindName("FileNameHolder");

            Images.Remove((from c in Images where c.ImageName == t.Text select c).FirstOrDefault());
        }
    }
}